package com.example.demo;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity  implements IOnChanceListen{
    private ListView lvStulist;
    private ImageView ivSearch;
    private Button btnAdd;
    private ArrayList<Student> studentArrayList = new ArrayList<>();
    private StudentAdapter adapter;
    private ImageView ivDel;
    private EditText edtKey;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findView();
        adapter = new StudentAdapter(MainActivity.this,studentArrayList,MainActivity.this);
        readDataFromDB();
        lvStulist.setAdapter(adapter);

        //编辑功能
        lvStulist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Student student = studentArrayList.get(position);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,EditActivity.class);
                intent.putExtra("STUNO", student.getStuNo());
                intent.putExtra("NAME", student.getStuName());
                intent.putExtra("AGE", student.getStuAge());
                startActivityForResult(intent, 1002);
            }
        });







    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == 2001){
            String stuno = data.getStringExtra("STUNO");
            String stuname = data.getStringExtra("STUNAME");
            int    stuage  = data.getIntExtra("STUAGE",0);

            Student student = new Student(stuno,stuname,stuage);
            addStudentToDB(student);
        }else if(resultCode==3001){
            String stuno = data.getStringExtra("STUNO");
            String stuname = data.getStringExtra("STUNAME");
            int    stuage  = data.getIntExtra("STUAGE",0);

            Student student = new Student(stuno,stuname,stuage);
            updateStudentToDB(student);
        }
    }

    /**
     * 更改数据库数据
     * @param student
     */
    private void updateStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("name", student.getStuName());
        values.put("age", student.getStuAge());
        String where = "stuno = '"+student.getStuNo()+"'";
        db.update("student", values, where, null);
        db.close();
        readDataFromDB();
    }

    /**
     * 添加学生到数据库中
     * @param student
     */
    private void addStudentToDB(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        ContentValues values = new ContentValues();
        values.put("stuno",student.stuNo);
        values.put("name",student.getStuName());
        values.put("age",student.getStuAge());

        db.insert("student",null,values);
        readDataFromDB();
    }

    /**
     * 读取资料从DB
     */
    private void readDataFromDB() {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String sql = "create table if not exists student (stuno varchar(20), name varchar(20), age int)";
        db.execSQL(sql);

        studentArrayList.clear();
        Cursor cursor = db.query("student", null,null,
                null,null,null,null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }

        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();
    }

    /**
     * 初始化
     */
    private void findView() {
        lvStulist = findViewById(R.id.lv_stu);

        btnAdd    = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,addStudent.class);
                startActivityForResult(intent,1001);
            }
        });

        edtKey    = findViewById(R.id.edt_key);
        ivSearch = findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = edtKey.getText().toString();
                searchFromDB(key);
            }
        });



        ivDel = findViewById(R.id.iv_delect);

    }

    /**
     * 查询
     * @param key
     */
    private void searchFromDB(String key) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "stuno like '%"+key+"%' OR name like '%"+key+"%' OR age ="+key;

        studentArrayList.clear();
        Cursor cursor = db.query("student", null,where,
                null,null,null,null,null);

        if(cursor != null && cursor.getCount() > 0){
            for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
                String stuno = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);

                Student  student = new Student(stuno, name, age);
                studentArrayList.add(student);
            }
        }

        adapter.notifyDataSetChanged();

        cursor.close();
        db.close();
    }

    @Override
    public void delect(Student student) {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null);

        String where = "stuno='"+student.getStuNo()+"'";
        db.delete("student",where,null);
        db.close();
        readDataFromDB();
    }
}
